/*******************************************************************************
 * Copyright (c) 2010, 2030 www.mahao.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package cn.itlaobing.eshopmanagement.untils;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Part;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

/**
 * ClassName: ImgUploadUtil <br/>
 * Function: TODO 功能描述 <br/>
 * date: 2017年5月31日 上午8:31:42 <br/>
 * 
 * @author Mmmmm
 * @version
 * @since JDK 1.8
 */

public class ImgUploadUtil {
	static Log log = LogFactory.getLog(ImgUploadUtil.class);

	public static String upload(InputStream in ,String name) {
		Configuration cfg = new Configuration(Zone.zone2());

		UploadManager uploadManager = new UploadManager(cfg);

		// 以下的key我已经申请好的，可以使用
		String accessKey = "MboNV0VZMN_gNBzAJ5axLJhcWg_fcACZk7KtKK5V";
		String secretKey = "VEKXKzXg9UT1nyl8_8J765cGylWLRLWR1YTkGveK";
		String bucket = "test";
		String domain = "oolrr0jj6.bkt.clouddn.com";

		// 七牛的api
		// 默认不指定key的情况下，以文件内容的hash值作为文件名
		String key = name;

		Auth auth = Auth.create(accessKey, secretKey);
		String upToken = auth.uploadToken(bucket);

		try {
			// 七牛的api
			Response qnResponse = uploadManager.put(in, key, upToken, null, null);
			log.info(qnResponse);
			String responseBody = qnResponse.bodyString();

			JSONObject responseBodyJson = JSON.parseObject(responseBody);

			String hashValue = responseBodyJson.getString("hash");

			// 圖片地址
			String imageUrl = "http://" + domain + "/" + name;

			// map集合用于放置图片的url
			Map<String, String> map = new HashMap<String, String>();

			// map的键
			String imgkey = "url";

			map.put(imgkey, imageUrl);

			// 调用Gson将map集合转成json
			Gson gson = new Gson();

			String jsondata = gson.toJson(map);
			return jsondata;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
}
